import { Controller } from 'egg';
import MsgEnum from '../util/msgEnum';
import { Result } from '../util/result';
import { get, isExistObject } from '../util/ossFile';
import RoleEnum from '../util/roleEnum';

import xlsx from 'node-xlsx';

import sendToWormhole from 'stream-wormhole';

const toArray = require('stream-to-array');
export default class PatentController extends Controller {
  public async getPatentMaps() {
    const { ctx } = this;
    const data = await this.ctx.service.patent.getPatentMaps();
    if (data) {
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);

    } else {
      ctx.status = 400;
      ctx.body = new Result(data, MsgEnum.GET_FINANCIAL_LIST_SUCCESS);

    }
  }

  public async checkPatent() {
    const { ctx } = this;
    // 参数验证

    const { patentNumber } = ctx.query;

    const results = await this.ctx.service.patent.check(patentNumber);
    ctx.body = new Result(results);
  }

  public async uploadPatents() {
    const { ctx } = this;
    const r = await ctx.getFileStream();

    try {
      const newBuffer = await toArray(r).then(function (parts) {
        const buffers = [];
        for (let i = 0, l = parts.length; i < l; ++i) {
          const part = parts[i];
          buffers.push((part instanceof Buffer) ? part as never : new Buffer(part) as never);
        }
        return Buffer.concat(buffers);
      });
      const parse = xlsx.parse(newBuffer, {
        bookType: 'xlsx',
        bookSST: false,
        type: 'buffer',
      });
      const errorData: any[][] = [
        [
          '问题数据所在行',
          '问题详情',
        ],
      ];
      let OKnum = 0;
      let falseNUM = 0;
      for (let i = 0; i < parse[0].data.length - 3; i++) {
        const data = parse[0].data.slice(3)[i];
        const result = await this.ctx.service.patent.createUploadPatent(
          data[0],
          data[1],
          data[2],
          data[3],
          data[4],
          data[5],
          data[6],
          data[7],
          data[8],
          data[9],
          data[10],
          data[11],
          data[12],
          data[13]
        );
        if (result?.state === 'true') {
          OKnum++;
        } else {
          falseNUM++;
          errorData.push([]);
          errorData[errorData.length - 1].push(i + 4);
          errorData[errorData.length - 1].push(result?.message);
        }
      }
      ctx.body = {
        true: OKnum,
        errorData,
        false: falseNUM
      };
    } catch (err) {
      // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
      await sendToWormhole(r);
      throw err;
    }
  }
  public async list() {
    const { ctx } = this;

    const patents = await ctx.model.Patent.findAll({
      include: [
        { model: ctx.model.ApplicationArea },
        { model: ctx.model.Talent },
      ],
    });


    const result = patents.map(item => {
      const obj: any = item.toJSON();
      obj.applicationAreaName =
        (item as unknown as any)?.application_area?.name ?? '';
      return obj;
    });

    ctx.body = new Result({ patents: result }, MsgEnum.LOGIN_SUCCESS);
  }

  public async create() {
    const { ctx } = this;

    await ctx.getFileStream()
      .then(async r => {
        console.log(r);

        const result = await this.ctx.service.patent.insertPatent(r.fields, r);
        if (result.mainData) {
          ctx.body = result;
        } else {
          ctx.status = 406;
          ctx.body = result;
        }
      });
  }

  public async update() {
    const { ctx } = this;

    await ctx.getFileStream()
      .then(async r => {
        console.log(r);

        const result = await this.ctx.service.patent.updatePatent(r.fields, r);
        if (result.mainData) {
          ctx.body = result;
        } else {
          ctx.status = 406;
          ctx.body = result;
        }
      });
  }

  public async delete() {
    const { ctx } = this;
    const { id } = ctx.request.query;
    const result = await this.ctx.service.patent.delete(Number(id));
    if (result.mainData) {
      ctx.body = result;
    } else {
      ctx.status = 400;
      ctx.body = result;
    }
  }

  public async getPatentAttachment() {
    const { ctx } = this;

    const { id } = ctx.query;
    const result = await get(RoleEnum.PATENT, Number(id), '.pdf');
    if (result.error) {
      ctx.status = 400;
      ctx.body = result;
    } else {
      this.ctx.attachment(result.file_name);
      this.ctx.set('Content-Type', 'application/octet-stream');
      ctx.body = result.result.stream;
    }
  }

  public async hasFile() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    const res = await isExistObject(RoleEnum.PATENT, Number(id), '.pdf');
    if (res?.exist) {
      ctx.body = new Result(res, res.msg);
    } else {
      ctx.status = 404;
      ctx.body = new Result(res, res.msg);
    }
  }
}
